const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const rimraf = require('rimraf')
const webpack = require('webpack')

function resolve (...src) {
  return path.resolve(__dirname, ...src)
}

/**
 * 生成各个部分的HTML
 * @returns
 */
function createHtmlTemplate () {
  const htmlMap = [ 'homepage', 'background', 'options', 'popup' ]
  return htmlMap.map((item) => new HtmlWebpackPlugin({
    filename: item + '.html',
    template: './template/background.ejs',
    inject: 'body',
    chunks: [ item ],
  }))
}

console.log('环境', process.env.NODE_ENV)
if (process.env.NODE_ENV === "production") {
  rimraf("dist", {}, () => console.log("Removed all previous build assets.")); 
}

module.exports = {
  mode: 'development',
  entry: {
    background: './src/background.ts',
    popup: './src/popup.tsx',
    content: './src/content.ts',
    homepage: './src/homepage.tsx',
    options: './src/options.tsx',
  },
  output: {
    filename: '[name].js',
    path: resolve('dist'),
    publicPath: '/',
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.jsx' ],
    alias: {
      '@': resolve('src'),
    },
  },
  module: {
    rules: [
      {
        test: /\.(tsx|ts|js|jsx)?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
          { loader: 'sass-loader' },
        ],
      },
    ],
  },
  ...(process.env.NODE_ENV!=='production'?{devtool:'inline-source-map'}:{}),
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'src/manifest.json', to: 'manifest.json' },
        { from: 'src/assets', to: 'assets' },
        { from: 'src/_locales', to: '_locales' },
      ],
    }),
    ...createHtmlTemplate(),
    new webpack.HotModuleReplacementPlugin(),
  ],

}
